package com.javaziliao.design.service;

import com.javaziliao.design.ordermanagement.command.OrderCommand;
import com.javaziliao.design.ordermanagement.command.OrderCommandInvoker;
import com.javaziliao.design.ordermanagement.state.OrderState;
import com.javaziliao.design.ordermanagement.state.OrderStateChangeAction;
import com.javaziliao.design.pojo.Order;
import com.javaziliao.design.utils.RedisCommonProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Service;

@Service
public class OrderService {
    @Autowired
    private StateMachine<OrderState, OrderStateChangeAction> orderStateMachine;
    @Autowired
    private StateMachinePersister<OrderState, OrderStateChangeAction, String> stateMachineRedisPersister;
    @Autowired
    private RedisCommonProcessor redisCommonProcessor;
    @Autowired
    private OrderCommand orderCommand;

    public Order createOrder(String productId) {
        String orderId = "OID" + productId;
        Order order = Order.builder()
                .orderId(orderId)
                .productId(productId)
                .orderState(OrderState.ORDER_WAIT_PAY)
                .build();
        redisCommonProcessor.set(orderId, order, 900);
        OrderCommandInvoker invoker = new OrderCommandInvoker();
        invoker.invoke(orderCommand, order);
        return order;
    }

    public Order pay(String orderId) {
        Order order = (Order) redisCommonProcessor.get(orderId);

        // 包装Message
        Message<OrderStateChangeAction> message = MessageBuilder.withPayload(OrderStateChangeAction.PAY_ORDER)
                .setHeader("order", order).build();
        // Message传递给Spring状态机
        if (changeStateAction(message, order)) {
            return order;
        }
        return null;
    }

    public Order send(String orderId) {
        Order order = (Order) redisCommonProcessor.get(orderId);
        Message<OrderStateChangeAction> message = MessageBuilder.withPayload(OrderStateChangeAction.SEND_ORDER)
                .setHeader("order", order).build();
        if (changeStateAction(message, order)) {
            return order;
        }
        return null;
    }

    public Order receive(String orderId) {
        Order order = (Order) redisCommonProcessor.get(orderId);
        Message<OrderStateChangeAction> message = MessageBuilder.withPayload(OrderStateChangeAction.RECEIVE_ORDER)
                .setHeader("order", order).build();
        if (changeStateAction(message, order)) {
            return order;
        }
        return null;
    }

    // 状态机相关操作
    private boolean changeStateAction(Message<OrderStateChangeAction> message, Order order) {
        try {
            // 启动状态机
            orderStateMachine.start();
            // 从redis缓存中读取状态机，缓存的key为orderId+"STATE"
            stateMachineRedisPersister.restore(orderStateMachine, order.getOrderId() + "STATE");
            // 将message发给OrderStateListener
            boolean res = orderStateMachine.sendEvent(message);
            // 将更改完状态的状态机存储到Redis缓存
            stateMachineRedisPersister.persist(orderStateMachine, order.getOrderId() + "STATE");
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            orderStateMachine.stop();
        }
        return false;
    }


}
